﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BasecampRestAPI;
using BasecampUI;

namespace SplitToDoList
{
	public class MainFormMediator
	{
		private readonly IMainForm _form;
		private IBaseCamp _camp;
		private IProject[] _projects;
		private IToDoList[] _toDoLists;
		private IToDoListItem[] _todoListItems;

		public static MainFormMediator GetInstance(IMainForm form)
		{
			return new MainFormMediator(form);
		}
		private MainFormMediator(IMainForm form)
		{
			_form = form;
		}

		public void Load()
		{
			if (!_form.GetBaseCampFromCredentials(out _camp))
			{
				return;
			}
			List<string> names = new List<string>();
			List<IProject> projects = new List<IProject>();
			foreach (IProject project in _camp.Projects)
			{
				names.Add(project.Name);
				projects.Add(project);
			}
			_projects = projects.ToArray();
			Array.Sort(names.ToArray(), _projects);
			foreach (IProject project in _projects)
			{
				_form.AddProject(project.Name);
			}
			_form.ProjectSelectedIndex = 0;
			_form.SplitButtonEnabled = false;
		}

		public void SourceProjectSelectedIndexChanged()
		{
			List<string> listNames = new List<string>();
			_toDoLists = _projects[_form.ProjectSelectedIndex].ToDoLists;
			foreach (IToDoList list in _toDoLists)
			{
				listNames.Add(list.Name);
			}
			Array.Sort(listNames.ToArray(), _toDoLists);
			_form.ClearToDoLists();
			foreach (IToDoList list in _toDoLists)
			{
				_form.ToDoListsAddItem(list.Name);
			}
		}

		private class CompareItemsByContent : IComparer<IToDoListItem>
		{
			#region IComparer<IToDoListItem> Members

			public int Compare(IToDoListItem x, IToDoListItem y)
			{
				return String.Compare(x.Content, y.Content);
			}

			#endregion
		}

		public void SourceToDoListSelectedIndexChanged()
		{
			_todoListItems = (_form.ToDoListSelectedIndex < _toDoLists.Length) ?
				_toDoLists[_form.ToDoListSelectedIndex].Items : new IToDoListItem[0];
			Array.Sort<IToDoListItem>(_todoListItems, new CompareItemsByContent());
			_form.ClearToDoListItems();
			foreach (IToDoListItem item in _todoListItems)
			{
				_form.ToDoListItemsAddItem(item.Content);
			}
		}

		public void NewListNameChanged()
		{
			_form.SplitButtonEnabled = _form.NewListName.Trim().Length > 0;
		}

		public void SplitButtonClicked()
		{
			IToDoList sourceList = _toDoLists[_form.ToDoListSelectedIndex];
			IProject sourceProject = _projects[_form.ProjectSelectedIndex];
			IToDoList newList = sourceProject.CreateToDoList(_form.NewListName,
				sourceList.Description, sourceList.Milestone, sourceList.Private, sourceList.Tracked);
			foreach (int index in _form.SelectedListItems)
			{
				IToDoListItem sourceItem = _todoListItems[index];
				newList.CreateItem(sourceItem.Content, sourceItem.ResponsibleParty, true);
			}
		}
	}
}
